package com.wang.transfer.util.algorithm;

import java.math.BigDecimal;

/**
 * 有符号32位数字反转
 * 超过32位返回0
 */
public class NumReverse {

    public static void main(String[] args) {
        int x = 1111111119;
//        int reverse = new NumReverse().reverse(x);
        int reverse = new NumReverse().reverse2(x);
        System.out.println(reverse);
    }

    public int reverse(int x) {
        String s = String.valueOf(x);
        if (s.length() == 1) {
            return x;
        }
        char c = s.charAt(0);
        if (c == '-') {
            s = s.substring(1);
            if (s.length() == 1) {
                return x;
            }
        }
        StringBuilder stringBuilder = new StringBuilder(s);
        s = stringBuilder.reverse().toString();
        while(s.charAt(0) == '0') {
            s = s.substring(1);
        }
        // 避免出现科学计数法
        BigDecimal bigDecimal = BigDecimal.valueOf(Math.pow(2, 31));
        String max = bigDecimal.toPlainString();
        int size = s.length();
        if (size > 10) {
            return 0;
        }
        if (c == '-') {
            if (size == 10 && s.compareTo(max) > 0) {
                return 0;
            }
            x = Integer.parseInt(c + s);
        } else {
            if (size == 10 && s.compareTo(max) >= 0) {
                return 0;
            }
            x = Integer.parseInt(s);
        }
        return x;
    }

    /**
     * 官方
     * 在最后一位之前判断是否溢出
     */
    public int reverse2(int x) {
        int rev = 0;
        while (x != 0) {
            if (rev < Integer.MIN_VALUE / 10 || rev > Integer.MAX_VALUE / 10) {
                return 0;
            }
            int digit = x % 10;
            x /= 10;
            rev = rev * 10 + digit;
        }
        return rev;
    }
}
